//
//  SpeechSelector.m
//  dsBridge
//
//  Created by sxh on 2020/9/18.
//

#import "SpeechSelector.h"
#import "NSObject+UIViewController.h"
#import "ISRDataHelper.h"
#import <iflyMSC/iflyMSC.h>

@interface SpeechSelector()
<
    IFlyRecognizerViewDelegate
>

@property (nonatomic, strong) IFlyRecognizerView *recognizerView;

@property (nonatomic, strong) RecognizerCallBlock callBack;

@end

@implementation SpeechSelector

+ (instancetype)sharedInstace {
    static SpeechSelector *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[SpeechSelector alloc] init];
    });
    return shared;
}

- (void)startRecognizer:(RecognizerCallBlock)callBack {
    self.recognizerView.hidden = NO;
    [self.recognizerView start];
    _callBack = callBack;
}

- (void)stopRecognizer {
    [self.recognizerView cancel];
    // 识别完成之后关闭页面
    [self hiddenView];
}

/*!
 *  回调返回识别结果
 *
 *  @param resultArray 识别结果，NSArray的第一个元素为NSDictionary，NSDictionary的key为识别结果，sc为识别结果的置信度
 *  @param isLast      -[out] 是否最后一个结果
 */
- (void)onResult:(NSArray *)resultArray isLast:(BOOL) isLast {
    
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    NSString *resu = [ISRDataHelper stringFromJson:result];
    
    if (_callBack) {
        _callBack(resu,nil);
        // 识别完成之后关闭页面
        [self hiddenView];
    }
}

/*!
 *  识别结束回调
 *
 *  @param error 识别结束错误码
 */
- (void)onCompleted: (IFlySpeechError *) error {
    
    if (_callBack) {
        
        NSError *err = [[NSError alloc] initWithDomain:@"" code:error.errorCode userInfo:@{@"errMessage":error.errorDesc}];
        _callBack(nil, err);
    }
    // 识别完成之后关闭页面
    [self hiddenView];
}

//关闭页面
- (void)hiddenView {
    [UIView animateWithDuration:0.1 animations:^{
//        [self.recognizerView cancel];
        // 识别完成之后关闭页面
        self.recognizerView.hidden = NO;
    }];
}

- (IFlyRecognizerView *)recognizerView {
    if (!_recognizerView) {
        _recognizerView = [[IFlyRecognizerView alloc] initWithCenter:self.zlzk_viewController.view.center];
        [_recognizerView setAutoRotate:YES];
        [_recognizerView setParameter:@"iat" forKey: [IFlySpeechConstant IFLY_DOMAIN]];
        _recognizerView.delegate = self;
        [self.zlzk_viewController.view addSubview:_recognizerView];
    }
    return _recognizerView;
}

@end
